/*-------------------------------------------------- |

 | dTree 2.05 | www.destroydrop.com/javascript/tree/ |

 |---------------------------------------------------|

 | Copyright (c) 2002-2003 Geir Landr?               |

 |                                                   |

 | This script can be used freely as long as all     |

 | copyright messages are intact.                    |

 |                                                   |

 | Updated: 17.04.2003                               |

 |  luanmad changed at 05/2009                        |
 
 |  id,pid,name,url,sort are required                 |
 
 |  powered by www.zoomhoo.com                       |
 |--------------------------------------------------*/

// Node object
function Node(id, pid, name, url, title, target, icon, sort, fontStyleName, iconOpen, open)
{
    this.id = id;
    this.pid = pid;
    this.name = name;
    this.url = url;
    this.title = myFilterDecode(title);
    this.target = target;
    this.icon = icon;
    this.iconOpen = iconOpen;
    this._io = open || false;
    this.sort = sort;
    this.fontStyleName = fontStyleName;
    this._is = false;
    this._ls = false;
    this._hc = false;
    this._ai = 0;
    this._p;
}

// Tree object
function dTree(objName, htmlContainer)
{
    this.config = {target:null, folderLinks:false, useSelection:true, useCookies:true, useLines:true, useIcons:true, useStatusText:false, closeSameLevel:false, inOrder:false};
    this.icon = {root:"images/ajax_dtree/folder.gif", folder:"images/ajax_dtree/folder.gif", folderOpen:"images/ajax_dtree/folderopen.gif", node:"images/ajax_dtree/folder.gif", empty:"images/ajax_dtree/empty.gif", line:"images/ajax_dtree/line.gif", join:"images/ajax_dtree/join.gif", joinBottom:"images/ajax_dtree/joinbottom.gif", plus:"images/ajax_dtree/plus.gif", plusBottom:"images/ajax_dtree/plusbottom.gif", minus:"images/ajax_dtree/minus.gif", minusBottom:"images/ajax_dtree/minusbottom.gif", nlPlus:"images/ajax_dtree/nolines_plus.gif", nlMinus:"images/ajax_dtree/nolines_minus.gif"};
    this.obj = objName;
    this.aNodes = [];
    this.aNodesData = [];
    this.container = htmlContainer || "dtree";
    this.aIndent = [];
    this.root = new Node(-1);
    this.selectedNode = null;
    this.selectedFound = false;
    this.completed = false;
}

// Adds a new node to the node array
dTree.prototype.add = function (id, pid, name, url, title, target, icon, sort, fontStyleName, iconOpen, open)
{
    //this.aNodesData[this.aNodesData.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open);
    this.aNodesData[this.aNodesData.length] = new Node(id, pid, name, url, title, target, icon, sort, fontStyleName, iconOpen, open);
};

// Open/close all nodes
dTree.prototype.openAll = function ()
{
    this.oAll(true);
};
dTree.prototype.closeAll = function ()
{
    this.oAll(false);
};

// Outputs the tree to the page
dTree.prototype.toString = function ()
{
    var str = "<div class=\"dtree\">\n";
    if (document.getElementById)
    {
        if (this.config.useCookies)
        {
            this.selectedNode = this.getSelected();
        }
//        alert(this.root);
        str += this.addNode(this.root);
    }
    else
    {
        str += "Browser not supported.";
    }
    str += "</div>";
    if (!this.selectedFound)
    {
        this.selectedNode = null;
    }
    this.completed = true;
    return str;
};

// Creates the tree structure // auto initialized
dTree.prototype.addNode = function (pNode) {
	var str = "";
	var n = 0;
	if (this.config.inOrder) {

		//alert("pNode._ai="+pNode._ai);//luanmad added
		n = pNode._ai;
	}
	for (n; n < this.aNodes.length; n++) {
		if (this.aNodes[n].pid == pNode.id) {
			var cn = this.aNodes[n];
			cn._p = pNode;
			//cn._ai = n;
			cn._ai = this.aNodes[n].id;//luanmad changed
			//alert("cn._ai="+cn._ai);
			this.setCS(cn);
			if (!cn.target && this.config.target) {
				cn.target = this.config.target;
			}
			if (cn._hc && !cn._io && this.config.useCookies) {
				cn._io = this.isOpen(cn.id);
			}
			if (!this.config.folderLinks && cn._hc) {
				cn.url = null;
			}
			if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) {
				cn._is = true;
				//this.selectedNode = n;//original code
				this.selectedNode = this.aNodes[n].id;//luanmad changed
				this.selectedFound = true;
			}
			//str += this.node(cn, n);//original code
			str += this.node(cn, this.aNodes[n].id);//luanmad changed , may be aNodes index (n) is not euqals aNodes array 's id (eg. aNodes index is 0,but the id in the aNodes arrsy is 1000)

			if (cn._ls) {
				break;
			}
		}
	}
	return str;
};

// Creates the node icon, url and text
dTree.prototype.node = function (node, nodeId)
{
    
    var divSelected = "onmouseover = \"this.style.backgroundColor='#FFF250';\" onmouseout = \"this.style.backgroundColor='#FFFFFF';\"";
    var str = "<div  "+divSelected+"  class=\"dTreeNode\">" + this.indent(node, nodeId);
    if (this.config.useIcons)
    { 
        if (!node.icon)
        {
            node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);
        }
        if (!node.iconOpen)
        {
            node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
        }
        if (this.root.id == node.pid)
        {
            node.icon = this.icon.root;
            node.iconOpen = this.icon.root;
            
        }
        str += "<span style=\"width:300px;overflow:hidden; text-overflow:ellipsis; white-space:nowrap;\"><img id=\"i" + this.obj + nodeId + "\" src=\"" + ((node._io) ? node.iconOpen : node.icon) + "\" alt=\"\" />";
    }
    if (node.url)
    {
        str += "<a id=\"s" + this.obj + nodeId + "\"  class=\"" + ((this.config.useSelection) ? ((node._is ? "nodeSel" : "node")) : "node") + "\" href=\"" + node.url + "\"";
        if (node.title)
        {
            str += " title=\"" + node.title + "\"";
        }
        if (node.target)
        {
            str += " target=\"" + node.target + "\"";
        }
        if (this.config.useStatusText)
        {
            str += " onmouseover=\"window.status='" + node.name + "';return true;\" onmouseout=\"window.status='';return true;\" ";
        }
        if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc))
        {
            str += " ondblclick=\"javascript: " + this.obj + ".s(" + nodeId + ");\"";
        }
        str += " >";//link to the page that named 'frmView'
        //str += "<a href='/StoreAdmin/inventory/products/index.jsp?pftype=" + nodeId + "' target=\"" + node.target + "\"  class=\"node\" >";//luanmad changed
    }
    else
    {
        if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id)
        {
            //str += "<a href="javascript: " + this.obj + ".o(" + nodeId + ");" class="node" >";//original code
            str += "<a href=\"javascript: " + this.obj + ".o(" + nodeId + ");\" class=\"node\" >";//luanmad changed
            //str += "<a href='/StoreAdmin/inventory/products/index.jsp?pftype=" + nodeId + "' target=\"" + node.target + "\" title=\""+node.title+"\"  class=\"node\" >";//luanmad changed
        }
    }
    //original code
    //str += node.name;
    //***************************** start ****************************
    //luanmad added
    var count = this.countChildren(nodeId);//count a node has how many children
    //show name of a node and add some function near it (+aaa add modify delete)
    //    var addNodeLink   = " <a class='thickbox' href='add.jsp?catid="+nodeId+"&keepThis=true&TB_iframe=true&height=550&width=777'"+" target='frmView' onclick='"+this.obj+".delegateAdd("+nodeId+")'  >&nbsp;&nbsp;add</a> ";
    //	var updateNodeLink   = " <a class='thickbox' href='edit.jsp?editid="+nodeId+"'  target='frmView' onclick='"+this.obj+".delegateUpdate("+nodeId+")'  >&nbsp;&nbsp;update</a> ";
    //    var addNodeLink   = " <a class='thickbox' href='javascript:void(0);' onclick='"+this.obj+".delegateAdd("+nodeId+",\""+myFilterDecode(node.name)+"\")'  >&nbsp;&nbsp;add</a> ";
    var addNodeLink = " <a class='thickbox' href='javascript:void(0);'  onclick='" + this.obj + ".delegateAdd(" + nodeId + ",\"" + node.name + "\")'  >&nbsp;&nbsp;添加</a> ";
    var updateNodeLink = " <a class='thickbox' href='javascript:void(0);' onclick='" + this.obj + ".delegateUpdate(" + nodeId + "," + node.sort + ")'  >&nbsp;&nbsp;修改</a> ";
    var deleteNodeLink = " <a href='javascript:void(0);'  onclick='" + this.obj + ".delegateRemove(" + nodeId + ")'  >&nbsp;&nbsp;删除</a> ";
    //    var deleteNodeLink = '<a href="#" onClick="javascript:alertreadme('<%=getString("确定删除类别")%>: <%=o.getCatname().replaceAll("\'","\\\\\'").replaceAll("\"","\\\\\"")%> ?','del.jsp?catid=<%=o.getId()%>')"><U><%=getString("确定删除类别")%></U></a>';
    //    var deleteNodeLink = "<a href=\"#\" onClick=\"javascript:alertreadme(\"Do Delete :"+node.name+".replaceAll(\"\'\",\"\\\\\'\").replaceAll(\"\"\",\"\\\\\"\")%> ?','=<%=o.getId()%>')"><U><%=getString("确定删除类别")%></U></a>';
    var upImageLink = " <a href='javascript:void(0);'  onclick='" + this.obj + ".delegateSort(" + node.sort + "," + nodeId + ",\"DOWN\"" + ")'  ><img src='images/ajax_dtree/down2.gif' alt='下移'></a> ";
    var downImageLink = " <a href='javascript:void(0);'  onclick='" + this.obj + ".delegateSort(" + node.sort + "," + nodeId + ",\"UP\"" + ")'  ><img src='images/ajax_dtree/up2.gif' alt='上移'></a> ";
    //    var showProductCountLink =  " <a class='thickbox' href='javascript:void(0);' onclick='"+this.obj+".delegateCount("+nodeId+")'  >&nbsp;&nbsp;showProductCount</a> ";
    var showProductCountLink = " <a class='tooltips' href='javascript:void(0);' onmouseover='" + this.obj + ".delegateCount(" + nodeId + ")'  >&nbsp;&nbsp;显示本类别商品数</a> ";
    //var modifyNodeLink = " <a href='aaa.jsp' target='frmView' onclick='"+this.obj+".delegateModify("+nodeId+")'  >&nbsp;&nbsp;modify</a> ";
    //alert("nodeName="+node.name+",\n myFilterDecode nodeName = "+myFilterDecode(node.name));

    //	str += node.name +" ["+count+"] " + "<a href=\"javascript: " + this.obj + ".show(" + nodeId + ");\">&nbsp;&nbsp;add </a>"+"<a href=\"javascript: " + this.obj + ".show(" + nodeId + ");\">&nbsp;&nbsp;modify </a>"+"<a href=\"javascript: " + this.obj + ".show(" + nodeId + ");\">&nbsp;&nbsp;delete </a>";
    /*if(node.sort == this.getMaxNodeId())
     {
     str += node.name +" ["+count+"] " +addNodeLink+updateNodeLink+deleteNodeLink+upImageLink+downImageLink+" id="+node.id+" sort="+node.sort+" max" +modifyNodeLink;
     }
     else
     str += node.name +" ["+count+"] " +addNodeLink+updateNodeLink+deleteNodeLink+upImageLink+downImageLink+" id="+node.id+" sort=" +node.sort+modifyNodeLink ;
     */
    // show the UP arrow or DOWN arrow	or both
    var countChildrenByPid = this.countChildren(node.pid);
    var flag = false ;

    if (this.root.id == node.pid)
    {
        str += myFilterDecode(node.fontStyleName) + " [" + count + "]</span> "  +"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+ addNodeLink ;//+  showProductCountLink;
    }
    else if (countChildrenByPid <= 1)
    {
        // decode node name from cts_category_dtree's
        // no children , no up and down
//        str += myFilterDecode(node.fontStyleName) + " [" + count + "]</span> " + addNodeLink + updateNodeLink + deleteNodeLink + showProductCountLink+"("+node.id+")";
        str += myFilterDecode(node.fontStyleName) + " [" + count + "]</span> " + addNodeLink + updateNodeLink + deleteNodeLink ;

    }
    else if (this.onlyMoveDown(node.pid, node.sort, countChildrenByPid))
    {
        // the first child , only can move down
//        str += myFilterDecode(node.fontStyleName) + " [" + count + "]</span> " + addNodeLink + updateNodeLink + deleteNodeLink +"&nbsp;&nbsp;&nbsp;&nbsp;"+ downImageLink  + showProductCountLink+"("+node.id+")";
        str += myFilterDecode(node.fontStyleName) + " [" + count + "]</span> " + addNodeLink + updateNodeLink + deleteNodeLink +"&nbsp;&nbsp;&nbsp;&nbsp;"+ downImageLink ;
        //alert("str="+str);
    }
    else if (this.onlyMoveUp(node.pid, node.sort, countChildrenByPid))
        {
            // the last child , only can move up
//            str += myFilterDecode(node.fontStyleName) + " [" + count + "]</span> " + addNodeLink + updateNodeLink + deleteNodeLink + upImageLink +"&nbsp;&nbsp;&nbsp;&nbsp;"+ showProductCountLink+"("+node.id+")";
            str += myFilterDecode(node.fontStyleName) + " [" + count + "]</span> " + addNodeLink + updateNodeLink + deleteNodeLink + upImageLink +"&nbsp;&nbsp;&nbsp;&nbsp;";
        }

        else
        {
            // the middle child , both can  move up and down
//            str += myFilterDecode(node.fontStyleName) + " [" + count + "]</span> " + addNodeLink + updateNodeLink + deleteNodeLink + upImageLink + downImageLink + showProductCountLink+"("+node.id+")";
            str += myFilterDecode(node.fontStyleName) + " [" + count + "]</span> " + addNodeLink + updateNodeLink + deleteNodeLink + upImageLink + downImageLink ;
        }
    //***************************** end  ****************************
    if (node.url || ((!this.config.folderLinks || !node.url) && node._hc))
    {
        str += "</a>";
    }
    str += "</div>";
    if (node._hc)
    {
        str += "<div id=\"d" + this.obj + nodeId + "\" class=\"clip\" style=\"display:" + ((this.root.id == node.pid || node._io) ? "block" : "none") + ";\">";
        str += this.addNode(node);
        str += "</div>";
    }
    this.aIndent.pop();
    return str;
};

// Adds the empty and line icons
dTree.prototype.indent = function (node, nodeId)
{
    //alert("node = "+node.name+" nodeId="+nodeId);
    var str = "";
    if (this.root.id != node.pid)
    {
        for (var n = 0; n < this.aIndent.length; n++)
        {
            str += "<img src=\"" + ((this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty) + "\" alt=\"\" />";
        }
        (node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);
        if (node._hc)
        {
            str += "<a href=\"javascript: " + this.obj + ".o(" + nodeId + ");\"><img id=\"j" + this.obj + nodeId + "\" src=\"";
            if (!this.config.useLines)
            {
                str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;
            }
            else
            {
                str += ((node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus));
            }
            str += "\" alt=\"\" /></a>";
        }
        else
        {
            str += "<img src=\"" + ((this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join) : this.icon.empty) + "\" alt=\"\" />";
        }
    }
    return str;
};


// Checks if a node has any children and if it is the last sibling
dTree.prototype.setCS = function (node)
{
    var lastId;
    for (var n = 0; n < this.aNodes.length; n++)
    {
        if (this.aNodes[n].pid == node.id)
        {
            node._hc = true;
        }
        if (this.aNodes[n].pid == node.pid)
        {
            lastId = this.aNodes[n].id;
        }
    }
    if (lastId == node.id)
    {
        node._ls = true;
    }
};

// Returns the selected node
dTree.prototype.getSelected = function ()
{
    var sn = this.getCookie("cs" + this.obj);
    return (sn) ? sn : null;
};

// Highlights the selected node
dTree.prototype.s = function (id)
{
    this.delegate(id);
    if (!this.config.useSelection)
    {
        return;
    }
    var cn = this.aNodes[id];
    if (cn._hc && !this.config.folderLinks)
    {
        return;
    }
    if (this.selectedNode != id)
    {
        if (this.selectedNode || this.selectedNode == 0)
        {
            eOld = document.getElementById("s" + this.obj + this.selectedNode);
            eOld.className = "node";
        }
        eNew = document.getElementById("s" + this.obj + id);
        eNew.className = "nodeSel";
        this.selectedNode = id;
        if (this.config.useCookies)
        {
            this.setCookie("cs" + this.obj, cn.id);
        }
    }
};

// Toggle Open or close
dTree.prototype.o = function (id)
{
    var cn;
    //alert("cn id ="+id);
    for (var i = 0; i < this.aNodes.length; i++)
    {

        if (this.aNodes[i].id == id)
        {
            cn = this.aNodes[i];
            //alert("true");
        }
    }
    //alert("cn.id="+cn.id);
    //	var cn = this.aNodes[id];
    //this.nodeStatus(!cn._io, id, cn._ls);
    this.nodeStatus(!cn._io, cn, cn._ls);
    cn._io = !cn._io;
    if (this.config.closeSameLevel)
    {
        this.closeLevel(cn);
    }
    if (this.config.useCookies)
    {
        this.updateCookie();
    }
    //this.delegate(id);//original code
};

//delegate,handle custom click event
dTree.prototype.delegate = function (id)
{
};


// Open or close all nodes
dTree.prototype.oAll = function (status)
{
    for (var n = 0; n < this.aNodes.length; n++)
    {
        if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id)
        {
            //this.nodeStatus(status, n, this.aNodes[n]._ls);
            this.nodeStatus(status, this.aNodes[n], this.aNodes[n]._ls);//luanmad changed
            this.aNodes[n]._io = status;
        }
    }
    if (this.config.useCookies)
    {
        this.updateCookie();
    }
};

// Opens the tree to a specific node
dTree.prototype.openTo = function (nId, bSelect, bFirst)
{
    if (!bFirst)
    {
//        alert("openTo nId = " + nId);
        for (var n = 0; n < this.aNodes.length; n++)
        {
            if (this.aNodes[n].id == nId)
            {
                nId = n;
                break;
            }
        }
    }
    var cn = this.aNodes[nId];
    if (cn.pid == this.root.id || !cn._p)
    {
        return;
    }
    cn._io = true;
    cn._is = bSelect;
    if (this.completed && cn._hc)
    {
        this.nodeStatus(true, cn._ai, cn._ls);
    }
    if (this.completed && bSelect)
    {
        this.s(cn._ai);
    }
    else
    {
        if (bSelect)
        {
            this._sn = cn._ai;
        }
    }
    this.openTo(cn._p._ai, false, true);
};


// Closes all nodes on the same level as certain node
dTree.prototype.closeLevel = function (node)
{
    //var num  = 0 ;
    //	alert("node = "+node.name+" this.aNodes.length="+this.aNodes.length);
    for (var n = 0; n < this.aNodes.length; n++)
    {
        if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc)
        {
            //num ++ ;
            //this.nodeStatus(false, n, this.aNodes[n]._ls);
            this.nodeStatus(false, this.aNodes[n], this.aNodes[n]._ls);// luanmad changed
            this.aNodes[n]._io = false;
            this.closeAllChildren(this.aNodes[n]);

        }
    }
    //alert("num = "+ num);

};

// Closes all children of a node
dTree.prototype.closeAllChildren = function (node)
{
    //var num = 0 ;
    //alert("node = "+node.name+" this.aNodes.length="+this.aNodes.length);
    for (var n = 0; n < this.aNodes.length; n++)
    {

        if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc)
        {
            //num ++ ;
            if (this.aNodes[n]._io)
            {
                //this.nodeStatus(false, n, this.aNodes[n]._ls);
                this.nodeStatus(false, this.aNodes[n], this.aNodes[n]._ls);//luanmad changed

            }

            this.aNodes[n]._io = false;
            this.closeAllChildren(this.aNodes[n]);
        }

    }
    //alert("num = "+ num);
};

// Change the status of a node(open or closed)
dTree.prototype.nodeStatus = function (status, node, bottom)
{
    //alert("nodeStatus.ID="+node.id);
    eDiv = document.getElementById("d" + this.obj + node.id);
    eJoin = document.getElementById("j" + this.obj + node.id);
    if (this.config.useIcons)
    {
        eIcon = document.getElementById("i" + this.obj + node.id);
        eIcon.src = (status) ? node.iconOpen : node.icon;
    }
    eJoin.src = (this.config.useLines) ? ((status) ? ((bottom) ? this.icon.minusBottom : this.icon.minus) : ((bottom) ? this.icon.plusBottom : this.icon.plus)) : ((status) ? this.icon.nlMinus : this.icon.nlPlus);
    eDiv.style.display = (status) ? "block" : "none";
    //alert("nodeStatus changed to :"+!status+" id = "+ node.id);//luanamd added
};

// [Cookie] Clears a cookie
dTree.prototype.clearCookie = function ()
{
    var now = new Date();
    var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
    this.setCookie("co" + this.obj, "cookieValue", yesterday);
    this.setCookie("cs" + this.obj, "cookieValue", yesterday);
};

// [Cookie] Sets value in a cookie
dTree.prototype.setCookie = function (cookieName, cookieValue, expires, path, domain, secure)
{
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + (expires ? "; expires=" + expires.toGMTString() : "") + (path ? "; path=" + path : "") + (domain ? "; domain=" + domain : "") + (secure ? "; secure" : "");
};

// [Cookie] Gets a value from a cookie
dTree.prototype.getCookie = function (cookieName)
{
    var cookieValue = "";
    var posName = document.cookie.indexOf(escape(cookieName) + "=");
    if (posName != -1)
    {
        var posValue = posName + (escape(cookieName) + "=").length;
        var endPos = document.cookie.indexOf(";", posValue);
        if (endPos != -1)
        {
            cookieValue = unescape(document.cookie.substring(posValue, endPos));
        }
        else
        {
            cookieValue = unescape(document.cookie.substring(posValue));
        }
    }
    return (cookieValue);
};


// [Cookie] Returns ids of open nodes as a string
dTree.prototype.updateCookie = function ()
{
    var str = "";
    for (var n = 0; n < this.aNodes.length; n++)
    {
        if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id)
        {
            if (str)
            {
                str += ".";
            }
            str += this.aNodes[n].id;
        }
    }
    this.setCookie("co" + this.obj, str);
};


// [Cookie] Checks if a node id is in a cookie
dTree.prototype.isOpen = function (id)
{
    var aOpen = this.getCookie("co" + this.obj).split(".");
    for (var n = 0; n < aOpen.length; n++)
    {
        if (aOpen[n] == id)
        {
            return true;
        }
    }
    return false;
};


// If Push and pop is not implemented by the browser
if (!Array.prototype.push)
{
    Array.prototype.push = function array_push()
    {
        for (var i = 0; i < arguments.length; i++)
        {
            this[this.length] = arguments[i];
        }
        return this.length;
    };
}
if (!Array.prototype.pop)
{
    Array.prototype.pop = function array_pop()
    {
        lastElement = this[this.length - 1];
        this.length = Math.max(this.length - 1, 0);
        return lastElement;
    };
}

////show the tree sequentially
//dTree.prototype.draw = function () {
//	// renew the two array to save original data.
//	this.aNodes = new Array();
//	this.aIndent = new Array();
//	// dump original data to aNode array.
//	for (var i = 0; i < this.aNodesData.length; i++) {
//		var oneNode = this.aNodesData[i];
//		this.aNodes[i] = new Node(oneNode.id, oneNode.pid, oneNode.name, oneNode.url, oneNode.title, oneNode.target, oneNode.icon ,oneNode.sort ,oneNode.fontStyleName , oneNode.iconOpen, oneNode.open);
//	}
//	this.rewriteHTML();
//};

//show the tree reversely // luanmad changed
dTree.prototype.draw = function ()
{
    // renew the two array to save original data.
    this.aNodes = new Array();
    this.aIndent = new Array();
    // dump original data to aNode array.
    var n=0;
    for (var i = this.aNodesData.length - 1; i >= 0; i--)
    {
        var oneNode = this.aNodesData[i];
        this.aNodes[n++] = new Node(oneNode.id, oneNode.pid, oneNode.name, oneNode.url, oneNode.title, oneNode.target, oneNode.icon, oneNode.sort, oneNode.fontStyleName, oneNode.iconOpen, oneNode.open);
    }
     this.rewriteHTML();
};

// outputs the tree to the page , callled by show()
dTree.prototype.rewriteHTML = function ()
{
    var str = "";
    var container;
    container = document.getElementById(this.container);
    if (!container)
    {
        alert("dTree can't find your specified container to show your tree.\n\n Please check your code!");
        return;
    }
    if (this.config.useCookies)
    {
        this.selectedNode = this.getSelected();
    }
//    str += this.addNode(this.root);
    str += this.addNode(this.root);
    if (!this.selectedFound)
    {
        this.selectedNode = null;
    }
    this.completed = true;
    container.innerHTML = str;
};

// Checks if a node has children
dTree.prototype.hasChildren = function (id)
{
    for (var i = 0; i < this.aNodesData.length; i++)
    {
        var oneNode = this.aNodesData[i];
        if (oneNode.pid == id)
        {
            return true;
        }
    }
    return false;
};

//define a remove method for Array
Array.prototype.remove = function (dx)
{
    if (isNaN(dx) || dx > this.length)
    {
        return false;
    }
    for (var i = 0, n = 0; i < this.length; i++)
    {
        if (this[i] != this[dx])
        {
            //this[n++] = this[i];
            this[n++] = this[i];
        }

    }
    this.length -= 1;
};

//remove a node
dTree.prototype.remove = function (id)
{
    if (!this.hasChildren(id))
    {
        for (var i = 0; i < this.aNodesData.length; i++)
        {
            if (this.aNodesData[i].id == id)
            {
                this.aNodesData.remove(i);
            }
        }
    }
};

//***************************** start ****************************
//luanmad added
dTree.prototype.show = function (id)
{
    alert("show id = " + id);
};

dTree.prototype.countChildren = function(id)
{
    var count = 0 ;
    for (var n = 0; n < this.aNodes.length; n++)
    {
        if (this.aNodes[n].pid == id)
        {
            count ++;
        }
    }
    //alert("id = "+id +" has "+count+" children ");
    return count;
};

dTree.prototype.getMaxNodeId = function()
{
    var maxNodeId = this.aNodes[0].id;
    for (var n = 1; n < this.aNodes.length; n ++)
    {
        if (maxNodeId < this.aNodes[n].id)
        {
            maxNodeId = this.aNodes[n].id;
        }
    }
    //alert("this.aNodes.length :"+this.aNodes.length);
    //alert(" getMaxNodeId = " + maxNodeId);
    return maxNodeId;
};

dTree.prototype.getCurrentNodeId = function(id)
{
    alert("current nodeId =" + id);

};

dTree.prototype.delegateAdd = function(id, name)
{
};

//dTree.prototype.delegateAdd = function(node)
//{
//};

dTree.prototype.delegateUpdate = function(id)
{
};

Array.prototype.update = function (id, pid, name)
{
    if (isNaN(id) || id > this.length)
    {
        return false;
    }

    for (var i = 0, n = 0; i < this.length; i++)
    {

        if (this[i] != this[id])
        {
            this[n++] = this[i];
        }
        else
        {
//            alert("this.id=" + this[i].id + ",pid=" + pid + ",name=" + name);
            this[n++] = new Node(this[i].id, pid, name, this[i].url, this[i].title, this[i].target, this[i].icon, this[i].sort, this[i].fontStyleName, this[i].iconOpen, this[i].open);
        }

    }
    //this.length -= 1;
};

dTree.prototype.update = function(id, pid, name)
{
    //if (!this.hasChildren(id)) {
    for (var i = 0; i < this.aNodesData.length; i++)
    {
        if (this.aNodesData[i].id == id)
        {
//            alert("updateMe this.aNodesData[i].id =" + this.aNodesData[i].id);
            this.aNodesData.update(i, pid, name);
        }
    }
    //}
};

dTree.prototype.delegateRemove = function(id)
{
};

dTree.prototype.delegateSort = function(sort, id, move)
{
};

dTree.prototype.getCurrentNodeName = function (id)
{
    var n;
    for (n = 0; n < this.aNodes.length; n++)
    {
        if (this.aNodes[n].id == id)
        {
            break;
        }
    }
    //alert("this.aNodes[n].name="+this.aNodes[n].name);
    return this.aNodes[n].name;
};

dTree.prototype.getCurrentNodePid = function (id)
{
    var n;
    for (n = 0; n < this.aNodes.length; n++)
    {
        if (this.aNodes[n].id == id)
        {
            break;
        }
    }
    //alert("this.aNodes[n].pid="+this.aNodes[n].pid);
    return this.aNodes[n].pid;
};

dTree.prototype.getCurrentNodeParentName = function (id)
{
    this.getCurrentNodeName(id);
};

dTree.prototype.onlyMoveDown = function (pid, sort, countChildren)
{
    //var countChildren = this.countChildren(pid);
    var i ;
    var count = 0;
    //if(countChildren > 1)
{

    for (i = 0; i < this.aNodes.length; i ++)
    {
        if (this.aNodes[i].pid == pid)
        {

            if (sort > this.aNodes[i].sort)
            {
                break;
            }
            count ++;
        }
    }

    if (count == countChildren)
    {
        return true;
    }
    else
    {
        return false;
    }
}
    /*else
     {
     return false;
     }*/
};

dTree.prototype.onlyMoveUp = function (pid, sort, countChildren)
{
    //var countChildren = this.countChildren(pid);
    var i ;
    var count = 0;
    //if(countChildren > 1)
{

    for (i = 0; i < this.aNodes.length; i ++)
    {
        if (this.aNodes[i].pid == pid)
        {

            if (sort < this.aNodes[i].sort)
            {
                break;
            }
            count ++;
        }
    }

    if (count == countChildren)
    {
        return true;
    }
    else
    {
        return false;
    }
}
    /*else
     {
     return false;
     }*/


};

Array.prototype.sort = function (dx, pid, sort)
{
    if (isNaN(dx) || dx > this.length)
    {
        return false;
    }

    for (var i = 0, n = 0; i < this.length; i++)
    {

        if (this[i] != this[dx])
        {
            this[n++] = this[i];
        }
        else
        {
            //alert("this.id="+this[i].id+",pid="+pid+",name="+name+",sort="+sort);
            this[n++] = new Node(this[i].id, pid, this[i].name, this[i].url, this[i].title, this[i].target, this[i].icon, sort, this[i].fontStyleName, this[i].iconOpen, this[i].open);
        }

    }
    //this.length -= 1;
};

dTree.prototype.sort = function(id, pid, sort)
{
    //if (!this.hasChildren(id)) {
    for (var i = 0; i < this.aNodesData.length; i++)
    {
        if (this.aNodesData[i].id == id)
        {
            //alert("updateMe this.aNodesData[i].id ="+this.aNodesData[i].id );
            this.aNodesData.sort(i, pid, sort);
        }
    }
    //}
};

dTree.prototype.getMaxSort = function ()
{
    var maxSort = this.aNodes[0].sort;
    for (var n = 1; n < this.aNodes.length; n ++)
    {
        if (maxSort < this.aNodes[n].sort)
        {
            maxSort = this.aNodes[n].sort;
        }
    }
    //alert(" getMaxSort = " + maxSort);
    return maxSort;
};

// count the category has how many product
dTree.prototype.delegateCount = function(id)
{
};

dTree.prototype.getCurrentNodeUrl = function(id)
{
	var n;
    for (n = 0; n < this.aNodes.length; n++)
    {
        if (this.aNodes[n].id == id)
        {
            break;
        }
    }
    //alert("this.aNodes[n].name="+this.aNodes[n].name);
    return this.aNodes[n].url;
	
};
//***************************** end ****************************
